package design.pattern.Lu01SingletonPattern;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @program JavaBase
 * @description: 单例模式
 * @author: zhanglu
 * @create: 2020-03-26 23:16:00
 */
public class Lu01SingletonPattern {

    public static void main(String[] args) {

        test02();

    }

    /**
     * 单例模式-破坏
     *  通过反射
     */
    private static void test01(){

        Person.getInstance();

        Class<?> c = Person.class;

        try {

            Field[] fields = c.getFields();

            Constructor<?> declaredConstructor = c.getDeclaredConstructor();

            declaredConstructor.setAccessible(true);

            Person o = (Person) declaredConstructor.newInstance();

            System.out.println(o);



        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 单例模式-破坏
     *  通过复制
     */
    private static void test02() {
        try {
            Person2 instance = Person2.getInstance();

            Person2 clone = (Person2) instance.clone();


            System.out.println(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

/**
    克隆下，单例模式会被破坏
    反射情况，可以通过代码逻辑去预防
 */
class Person{

    private static Person p = null;

    private static boolean isExist = false;

    private Person(){
        if(isExist){
            return;
        }
        isExist = true;
    }

    private String name = "1";

    public static Person getInstance(){
        if(p == null){
            p = new Person();
        }
        return p;
    }

}

class Person2 implements Cloneable{

    private final static Person2 p = new Person2();

    private Person2(){
        if(p != null){
            return;
        }
    }

    private String name = "zhangsan";

    public static Person2 getInstance(){
        return p;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}